/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
		'pageInit',
		'formValidator',
    'formAjax',
    'notification',
    'materialPreview',
    'select2',
    'holder',
    'uploadFiles'
	], function ($, vamakerPage, formValidator, formAjax, VamOpMsg, MaterialPreview, select2, holder, UploadFiles) {
  $(function () {
    var $dataFrm = $('#data-frm'),
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      dataFieldRule, options, dataValidator, sizeValidateCallback, urlValidateCallback,
      $materialSource = $('#material_source').find('input[name="material_source"]'),
      $localMaterial = $('#local_upload_material'),
      $customUrl = $('#custom_material_url'),
      $materialUrl = $('#custom_url'),
      creativeName = $('#creative_name').val(),
      $adspaceWidth = $('#adspace_width'),
      $adspaceHeight = $('#adspace_height');
    $materialSource.on('change', function(){
      var $me = $(this),
          meVal = $me.val();
      if (meVal === '1') {
        $customUrl.show();
        $localMaterial.hide();
      } else {
        $customUrl.hide();
        $localMaterial.show();
      }
    });
    $('input[name="material_source"]:checked').trigger('change');

      sizeValidateCallback = function (evt) {
        var $me = $(this),
        meVal = $me.val(),
        errorBox = $me.data('err'),
        $errorBox = $me.next('#'+errorBox),
        flag = true,
        msg = '';
        if (meVal === '') {
          flag = false;
          msg = VAM.j('Input cannot be empty!');
        } else if (!/^[0-9]*$/.test(meVal)) {
          flag = false;
          msg = VAM.j('Enter can only be integer!');
        } else if(parseInt(meVal,10) < 1) {
          flag = false;
          msg = VAM.j('Enter cannot be less than 1px!');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      };
    urlValidateCallback = function (evt) {
      var $me = $(this),
      meVal = $me.val(),
      errorBox = $me.data('err'),
      $errorBox = $('#'+errorBox),
      strRegex = '^((https|http|ftp|rtsp|mms)?://)'
      flag = true,
      re = new RegExp(strRegex),
      msg = '';
      if (meVal === '') {
        flag = false;
        msg = VAM.j('Material url cannot be empty!');
      } else if (!re.test(meVal)){
        flag = false;
        msg = VAM.j('Please input the correct target Url (starting with http:// or https://)');
      };
      if (!flag) {
        msg = '<em class="checky-default-failure">' + msg + '</em>';
        $errorBox.html(msg);
      } else {
        $errorBox.html('');
      };
    };
  $materialUrl.on('blur', urlValidateCallback);
  $adspaceWidth.on('blur', sizeValidateCallback);
  $adspaceHeight.on('blur', sizeValidateCallback);
    dataFieldRule = {
      creative_name:{
        rule:{
            required:{
                message:VAM.j('Creative cannot be empty')
            }
        },
        messageContainer:'creative_name_err'
      }
    };
    options = {
      submitOnSucceed: false,
      onvalidate: function(evt) {
        if (evt.resultList.length <= 0) {
          var $materialSource = $('#material_source').find('input[name="material_source"]:checked'),
              materialSourceVal = $materialSource.val();
          if (materialSourceVal === '0') {
            var materialVal = $('#upload_material').val(),
              $errorBox = $('#upload_material_err'),
              flag = true,
              msg = '';
            if (materialVal === '') {
              flag = false;
            };
            if (!flag) {
              msg = '<em class="checky-default-failure">' + VAM.j('Upload material cannot be empty') + '</em>';
              $errorBox.html(msg);
              return false;
            } else {
              $errorBox.html('');
            };
          } else {
            $materialUrl.trigger('blur', urlValidateCallback);
            $adspaceWidth.trigger('blur', sizeValidateCallback);
            $adspaceHeight.trigger('blur', sizeValidateCallback);
            var materialUrlErr = $('#custom_url_err').html(),
                adspaceWidthErr = $('#width_err').html(),
                adspaceHeightErr = $('#height_err').html();
            if (materialUrlErr !== '' || adspaceWidthErr !== '' || adspaceHeightErr !== '') {
              return false;
            }
          };
          $dataFrm.ajaxSubmit({
            beforeSubmit: function() {
              $submitBtn.button('loading');
            },
            success: function (data) {
              $submitBtn.button('reset');
              if (data.status === 'success') {
                VamOpMsg.messager(data);
                if (VAM.getVar('CLOSE_DIALOG_FLAG') === true) {
                  $('.creative-preview-modal', window.parent.document).find('.btn-default').trigger('click');
                } else {
                  var solution_id = '';

                  if ($('#solution_id').val()) {
                    var solution_id = '&solution_id=' + $('#solution_id').val();
                  }
                  window.location.href = VAM.getVar('NEXT_URL') + '?id=' + data.data.id + solution_id;
                }
              } else {
                VamOpMsg.messager(data);
              }
            }
          });
        };
      }
    };
    formValidator.validate($dataFrm, dataFieldRule, options);
    dataValidator = formValidator.dataValidator;
    dataValidator.addRule('effectiveNumber',function(val, opt){
      return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
    });
  });
  // Init Creative Upload.
  $(function () {
    var $uploadMaterial = $('#upload-material'),
      $uploadMaterialModal = $('#upload-material-modal'),
      $uploadMaterialInput = $('#upload_material'),
      $uploadMaterialOperate = $('#upload-confirm-operate'),
      $creativePreviewWrap = $('.creative-preview-wrap'),
      $creativeMaterialDefault = $('#creative_material_default');

    $uploadMaterialModal.on('hidden.bs.modal', function (evt) {
      var $me = $(this);
      $('#progress .progress-bar').css('width','0%').text('0%');
      $('#files').find('tbody').html('');
    });

    $uploadMaterial.on('click', function (evt) {
      var $me = $(this);
      $uploadMaterialModal.modal('show');
    });
 
    $uploadMaterialOperate.on('click', function(evt) {
      var $me = $(this),
        $uploadMaterialErr = $('#upload_material_err');
        materialId = $me.data('materialId'),
        prevewInfo = $me.data('materialInfo'),
        $placeHolder = $('#creative_material_default'),
        uploadType = $('#upload_type').val();
      evt.preventDefault();
      // console.log(prevewInfo);
      if (materialId !== '') {
        $uploadMaterialInput.val(materialId);
        $uploadMaterialModal.modal('hide');
        $uploadMaterialErr.html('');
        // TODO: creative material preview.
        MaterialPreview.previewSingle($('.creative-preview-wrap'), prevewInfo, materialId);
        $('#upload_material').trigger('blur');
      } else {
        $uploadMaterialInput.val('');
      };
    });
    $creativePreviewWrap.on('click', '.preview-close', function(evt) {
      var $me = $(this),
        $parent = $me.parent();
      evt.preventDefault();

      $parent.fadeOut(function() {
        $parent.remove();
        if ($creativePreviewWrap.find('.creative-preview').length === 0) {
          $creativeMaterialDefault.show();
          $("#upload_material").val("");
        };
      });
    });
  });
  // Upload Creative Material.
  $(function () {
      'use strict';
      var url = VAM.getVar('UPLOAD_MATERIAL_URL'),
          $fileUpload = $('#fileupload'),
          $progressBar = $('#progress .progress-bar'),
          $spaceHolder = $('#creative_material_default'),
          $previewImg = $('#creative_material_preview'),
          $table = $('#files').find('table tbody');
      $fileUpload.fileupload({
          url: url,
          dataType: 'json',
          done: function (e, data) {
            if (data.result.status === 'success') {
              var materialData = data.result.data,
               list = materialData['table'],
               listStr = '',
               imgUrl = materialData.preview.address;
              // console.log(imgUrl);
              // console.log(materialData);
              VamOpMsg.messager(data.result);
              listStr = '<tr>'
                      + '<td>' + materialData.id + '</td>'
                      + '<td>' + list.name + '</td>'
                      + '<td>' + list.size + '</td>'
                      + '<td>' + list.date + '</td>'
                      + '<td>' + list.judgeInfo + '</td>'
                      + '<td>' + list.updater + '</td>'
                      + '</tr>';
              $table.append(listStr);
              $('#upload-confirm-operate').data('materialId', materialData.id).data('materialInfo', materialData['preview']);
            }else {
              // VAM.fn.Messenger(data.result.reason, 'error');
              VamOpMsg.messager(data.result);
              $('#upload-confirm-operate').data('materialId', '');
            };
          },
          progressall: function (e, data) {
              var progress = parseInt(data.loaded / data.total * 100, 10);
              $progressBar.css('width','0%').text('0%');
              $progressBar.css(
                  'width',
                  progress + '%'
              ).text(progress + '%');
          }
      })
      .prop('disabled', !$.support.fileInput)
      .parent().addClass($.support.fileInput ? undefined : 'disabled');
  });
  //Creative Vocation.
  $(function(){
    var creativeVocation = $.parseJSON(VAM.getVar('CREATIVE_VOCATION')),
      $vocationLarge = $('#creative_vocation_large'),
      $vocationSmall = $('#creative_vocation_small');
    for(var key in creativeVocation){
      if(creativeVocation.hasOwnProperty(key)) {
        $vocationLarge.append('<option value="'+key+'">' + key + '</option>');
      }
    }

    $vocationLarge.on('change',function(){
      var $me = $(this),
        vocationSmall = creativeVocation[$me.val()],
        i,j;
      $vocationSmall.children().remove();
      $vocationSmall.append('<option value="' + VAM.j('All') + '">' + VAM.j('All') + '</option>');
      for (i=0, j=vocationSmall.length; i<j; i++) {
        $vocationSmall.append('<option value="' + vocationSmall[i] + '">' + vocationSmall[i] +'</option>');
      }
    });

    var creativeParentVocation = VAM.getVar('parent_category');
    var creativeChildVocation = VAM.getVar('child_category');

    $("#creative_vocation_large option[value='"+creativeParentVocation+"']").attr('selected', "selected");
    $vocationLarge.trigger('change');
    $("#creative_vocation_small option[value='"+creativeChildVocation+"']").attr('selected', "selected");
  })
});
